<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="医生名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入医生名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:doctor:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:doctor:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:doctor:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:doctor:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="doctorList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="true" label="主键id" align="center" prop="id" />
        <el-table-column label="医生名称" align="center" prop="name" />
        <el-table-column label="所属科室" align="center" prop="title" width="140" show-overflow-tooltip />
        <el-table-column label="头像" align="center" prop="photoUrl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.photoUrl" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="医生级别" align="center" prop="level"></el-table-column>
        <el-table-column label="年限" align="center" prop="years" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['system:doctor:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['system:doctor:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 所属科室 -->
    <el-dialog v-model="centerDialogVisible.visible" :title="centerDialogVisible.title" width="550px" destroy-on-close center @close="closeClick">
      <div class="top">
        <div class="keyword">
          <el-input v-model="input" placeholder="请输入科室进行搜索" clearable />
        </div>
        <div class="btn" @click="search">
          <el-button type="primary" icon="Search">Search</el-button>
        </div>
      </div>
      <div>
        <el-checkbox-group v-model="selectedOffice">
          <div class="checkbox-group">
            <el-checkbox v-for="item in office" :key="item.id" :value="item.id" size="large" border class="checkbox-item">
              {{ item.title }}
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeClick">取消</el-button>
          <el-button type="primary" @click="confirmSelection">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 添加或修改医生对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="40%" append-to-body>
      <el-form ref="doctorFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="头像" prop="photo">
          <image-upload v-model="form.photo" :limit="1" />
        </el-form-item>
        <el-form-item label="医生名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入医生名称" />
        </el-form-item>
        <el-form-item label="医生介绍" prop="intro">
          <editor v-model="form.intro" :min-height="192" />
        </el-form-item>
        <el-form-item label="擅长方向" prop="great">
          <editor v-model="form.great" :min-height="192" />
        </el-form-item>
        <el-form-item label="所属科室" prop="depId">
          <el-input :value="selectedOfficeTitles" placeholder="请输入科室" @click="administrative" />
        </el-form-item>
        <el-form-item label="医生级别" prop="level">
          <el-input v-model="form.level" placeholder="请输入医生级别" />
        </el-form-item>
        <el-form-item label="年限">
          <el-input v-model="form.years" placeholder="请输入年限" />
        </el-form-item>
        <el-form-item label="接诊" prop="virtuals">
          <el-input v-model="form.virtuals" placeholder="默认为0" />
        </el-form-item>
        <el-form-item label="问诊费" prop="price">
          <el-input v-model="form.price" placeholder="默认为0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Doctor" lang="ts">
import { computed } from 'vue';
import { listDoctor, getDoctor, delDoctor, addDoctor, updateDoctor } from '@/api/system/doctor';
import { listDep } from '@/api/system/dep';
import { DoctorVO, DoctorQuery, DoctorForm } from '@/api/system/doctor/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const selectedOffice = ref([]); //存储多个选中的科室ID
const office = ref([
  // 复选框选项
]);
const params = ref({
  title: ''
});
const input = ref('');
const doctorList = ref<DoctorVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const doctorFormRef = ref<ElFormInstance>();
const selectedOfficeDetails = ref<OfficeDetail[]>([]);

// 计算属性，将选中的科室用逗号连接
const selectedOfficeTitles = computed(() => {
  return selectedOfficeDetails.value.map((item) => item.title).join('，');
});

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const centerDialogVisible = reactive<DialogOption>({
  visible: false,
  title: ''
});

interface OfficeDetail {
  id: string | number;
  title: string;
}

const initFormData: DoctorForm = {
  id: undefined,
  name: undefined,
  depId: undefined,
  intro: undefined,
  great: undefined,
  plan: undefined,
  photo: undefined,
  level: undefined,
  price: undefined,
  virtuals: undefined,
  years: undefined
};
const data = reactive<PageData<DoctorForm, DoctorQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    depId: undefined,
    photo: undefined,
    level: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键id不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '医生名称不能为空', trigger: 'blur' }],
    depId: [{ required: true, message: '所属科室不能为空', trigger: 'change' }],
    intro: [{ required: true, message: '医生介绍不能为空', trigger: 'blur' }],
    photo: [{ required: true, message: '头像不能为空', trigger: 'blur' }],
    level: [{ required: true, message: '医生级别不能为空', trigger: 'change' }]
  }
});

// 确认选择的方法
const confirmSelection = () => {
  // 如果需要获取选中的科室详细信息
  selectedOfficeDetails.value = office.value.filter((item) => selectedOffice.value.includes(item.id));
  // 给form表单赋值
  form.value.depId = selectedOffice.value.join(','); // 将选中的科室ID以逗号分隔的形式赋值给depId
  // 关闭对话框
  centerDialogVisible.visible = false;
};
const { queryParams, form, rules } = toRefs(data);

// 关闭对话框的方法
const closeClick = () => {
  centerDialogVisible.visible = false;
  selectedOffice.value = []; // 关闭时清空选择
};

/** 查询医生列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDoctor(queryParams.value);
  doctorList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  selectedOffice.value = [];
  selectedOfficeDetails.value = [];
  doctorFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: DoctorVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
//搜索科室
const search = async () => {
  params.value.title = input.value;
  const res = await listDep(params.value);
  if (res.code == 200) {
    office.value = res.rows; // 如果获取成功，则将科室数据赋值给响应式变量 office
  } else {
    throw new Error(res.msg || '获取科室数据失败'); // 处理获取失败的情况
  }
};
// 科室选择框回显
const administrative = () => {
  centerDialogVisible.visible = true; // 将对话框的可见性设置为 true
  centerDialogVisible.title = '所属科室'; // 设置对话框的标题
};
/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  await search();
  dialog.visible = true;
  dialog.title = '添加医生';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: DoctorVO) => {
  reset();

  const _id = row?.id || ids.value[0];
  const res = await getDoctor(_id);
  await search();
  Object.assign(form.value, res.data);
  // 给depId转为数组
  if (res.data.depId) {
    // 转换为数字类型
    selectedOffice.value = String(res.data.depId)
      .split(',')
      .map((item) => Number(item));
  } else {
    selectedOffice.value = [];
  }
  selectedOfficeDetails.value = office.value.filter((item) => selectedOffice.value.includes(item.id));
  dialog.visible = true;
  dialog.title = '修改医生';
};

/** 提交按钮 */
const submitForm = () => {
  doctorFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateDoctor(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addDoctor(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: DoctorVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除医生编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delDoctor(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/doctor/export',
    {
      ...queryParams.value
    },
    `doctor_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
<style scoped>
.checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.checkbox-item {
  margin-right: 0;
  margin-bottom: 10px;
}
.top {
  display: flex;
  margin-bottom: 20px;
}

.keyword {
  width: 400px;
  margin-right: 20px;
}

.footer {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
